<template>
    <div class="work">
      <h1>调休申请表</h1>
      <el-form :model="formData" ref="formRef" :rules="rules">
        <p>申请人姓名：<el-input v-model="formData.name" placeholder="申请人姓名" style="width: 180px"/></p>  
        <div v-for="(item, index) in formData.items" :key="index">
            <p>开始时间：
              <el-date-picker
                v-model="item.starttime"
                type="datetime"
                placeholder="Select date and time"
              />
            </p>
            <p>结束时间：
              <el-date-picker
                v-model="item.endtime"
                type="datetime"
                placeholder="Select date and time"
              />
            </p>
            <p>时长(小时)：
              <el-input v-model="item.duration" placeholder="" style="width: 180px"/>
            </p>
            <p>上次加班开始时间：
              <el-date-picker
                v-model="item.last_starttime"
                type="datetime"
                placeholder="Select date and time"
              />
            </p>
            <p>上次加班结束时间：
              <el-date-picker
                v-model="item.last_endtime"
                type="datetime"
                placeholder="Select date and time"
              />
            </p>
        </div>
  
        <el-form-item label="工作流" prop="workflow">
          <el-select
            v-model="formData.workflow"
            placeholder="请选择工作流"
            size="large"
            style="width: 240px"
            :disabled="!worklist.length"
          >
            <el-option
              v-for="m in worklist"
              :key="m.id"
              :label="m.name"
              :value="m.id"
            />
          </el-select>
        </el-form-item>
  
        <el-form-item label="审批人1" prop="user">
          <el-select
            v-model="formData.user"
            placeholder="请选择审批人1"
            size="large"
            style="width: 240px"
            :disabled="!uselist.length"
          >
            <el-option
              v-for="m in uselist"
              :key="m.id"
              :label="m.name"
              :value="m.id"
            />
          </el-select>
        </el-form-item>
  
        <el-form-item label="审批人2" prop="next_audit">
          <el-select
            v-model="formData.next_audit"
            placeholder="请选择审批人2"
            size="large"
            style="width: 240px"
            :disabled="!uselist.length"
          >
            <el-option
              v-for="m in uselist"
              :key="m.id"
              :label="m.name"
              :value="m.id"
            />
          </el-select>
        </el-form-item>
        <p>审核状态
            <el-radio-group v-model="formData.task_status">
              <el-radio label="1" size="large">新建</el-radio>
              <el-radio label="2" size="large">审批中</el-radio>
              <el-radio label="3" size="large">完成</el-radio>
            </el-radio-group>
        </p>
  
        <el-button type="primary" @click="submitForm">确定</el-button>
      </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import http from '../http';
import { ElMessage } from 'element-plus';

const router = useRouter();
const formData = ref({
    name: '',
    items: [
        { starttime: null, endtime: null, duration: '', last_starttime: null, last_endtime: null }
    ],
    workflow: null,
    task_status: '1',
    user: null,
    next_audit: null
});

const formRef = ref(null);
const worklist = ref([]);
const uselist = ref([]);

const rules = onMounted(() => ({
    name: [{ required: true, message: '申请人姓名不能为空', trigger: 'blur' }],
    workflow: [{ required: true, message: '请选择工作流', trigger: 'change' }],
    user: [{ required: true, message: '请选择审批人1', trigger: 'change' }],
    next_audit: [{ required: true, message: '请选择审批人2', trigger: 'change' }]
}));

const getWorkList = async () => {
try {
    const res = await http.get('work/');
    worklist.value = res.data;
    console.log(worklist.value);
} catch (err) {
    ElMessage.error('加载工作流失败');
    console.error(err);
}
};

const getUserList = async () => {
try {
    const res = await http.get('adminuser/');
    uselist.value = res.data;
} catch (err) {
    ElMessage.error('加载审批人失败');
    console.error(err);
}
};

const submitForm = async () => {
if (formRef.value) {
    const valid = await formRef.value.validate();
    if (valid) {
    const plainData = {
        name: formData.value.name,
        params: JSON.stringify(formData.value.items.map(item => ({
        starttime: item.starttime?.toISOString(),
        endtime: item.endtime?.toISOString(),
        duration: item.duration,
        last_starttime: item.last_starttime?.toISOString(),
        last_endtime: item.last_endtime?.toISOString()
        }))),
        workflow: formData.value.workflow,
        user: formData.value.user,
        next_audit: formData.value.next_audit,
        task_status: formData.value.task_status
    };

    try {
        const res = await http.post('task/', plainData);
        ElMessage.success(res.data.msg);
    } catch (err) {
        ElMessage.error(err.response?.data.msg || '提交失败');
    }
    }
}
};

onMounted(() => {
    getWorkList();
    getUserList();
});
</script>

<style scoped>
.work{
    margin-left: 100px;
}
</style>